package jlib.component.tool
{
	
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	
	/**
	 * Sprite 객체를 포토샵의 핸드툴 처럼 움직입니다.
	 * @author Park Jong Hee
	 */	
	public class HandTool extends EventDispatcher implements ITool, IMouseInteractive
	{
		private var m_pressPoint:Point;
		private var m_canvasPoint:Point;
		
		private var m_stage:Stage;
		private var m_canvas:DisplayObject;
		
		/**
		 * HandTool  
		 * @param stage
		 * @param canvas
		 */		
		public function HandTool(canvas:DisplayObject=null): void 
		{ 
			m_canvas = canvas;
			m_pressPoint = new Point();
			m_canvasPoint = new Point();
		}
		
		private function mouseHandler( e:MouseEvent ): void 
		{
			switch(e.type){
				case MouseEvent.MOUSE_DOWN: press(e);
				break;
				case MouseEvent.MOUSE_MOVE: move(e);
				break;
				case MouseEvent.MOUSE_UP: release(e);
				break;
			}
		}
		
		public function press(e:MouseEvent): void
		{
			m_pressPoint.x = m_stage.mouseX, m_pressPoint.y = m_stage.mouseY;
			m_canvasPoint.x = m_canvas.x, m_canvasPoint.y = m_canvas.y;
			m_stage.addEventListener(MouseEvent.MOUSE_UP, mouseHandler, false, 9) ;
			m_stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseHandler, false, 9);
			dispatchEvent(e);
//			dispatchEvent(new Event(Event.CHANGE));
			
		}
		
		public function move( e:MouseEvent ): void 
		{
			var mouseDx:Number = m_stage.mouseX - m_pressPoint.x;
			var mouseDy:Number = m_stage.mouseY - m_pressPoint.y;
			m_canvas.x = (m_canvasPoint.x + mouseDx);
			m_canvas.y = (m_canvasPoint.y + mouseDy);
			dispatchEvent(e);
			dispatchEvent(new Event(Event.CHANGE));
		}
		
		public function release( e:MouseEvent ): void
		{
			m_stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseHandler);
			m_stage.removeEventListener(MouseEvent.MOUSE_UP, mouseHandler);
			dispatchEvent(e);
//			dispatchEvent(new Event(Event.CHANGE));
		}
		
		public function setCanvas(canvas:DisplayObjectContainer): void { 
			m_canvas = canvas;
			if(!m_canvas.stage) throw new Error("canvas는 addChild 되어야 됩니다.");
			m_stage = m_canvas.stage;
		}
		
		public function getPoint(): Point
		{
			var result:Point = new Point();
			if(!m_stage) return result;
			result.x = m_stage.mouseX;
			result.y = m_stage.mouseY;
			return result;
		}
		
		public function on() : void  
		{ 
			if(m_stage && m_canvas) m_canvas.addEventListener( MouseEvent.MOUSE_DOWN, mouseHandler ); 
		}
		
		public function off() : void 
		{ 
			if(m_stage && m_canvas) m_canvas.removeEventListener( MouseEvent.MOUSE_DOWN, mouseHandler ); 
		}

		public function update(e:Event=null):void {  } 
		
	}//c
}